package com.dy.yunying.biz.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Random;

/**
 * 图片验证码
 *
 * @author WangLi
 */
public class SCaptcha {
    // 图片的宽度。
    private int width = 180;
    // 字体宽度
    private int fontWidth = 20;

    // 图片的高度。
    private int height = 40;
    // 验证码字符个数
    private int codeCount = 4;
    // 验证码干扰线数
    private int lineCount = 40;
    // 验证码
    private String code = null;
    // 验证码图片Buffer
    private BufferedImage buffImg = null;

    private char[] codeSequence = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    // 常用颜色
    public static final int[][] COLOR = {
            {200, 135, 255}, {51, 153, 51}, {254, 210, 164}, {153, 102, 0},
            {153, 102, 153}, {51, 153, 153}, {102, 102, 255}, {90, 102, 204},
            {204, 51, 51}, {120, 153, 204}, {230, 101, 202}, {241, 10, 117}
    };

    // 生成随机数
    private static final Random random = new SecureRandom();

    public SCaptcha() {
        this.createCode(Color.WHITE);
    }

    /**
     * @param width  图片宽
     * @param height 图片高
     */
    public SCaptcha(int width, int height, Color color) {
        this.width = width;
        this.height = height;
        this.createCode(color);
    }

    /**
     * @param width     图片宽
     * @param height    图片高
     * @param codeCount 字符个数
     * @param lineCount 干扰线条数
     */
    public SCaptcha(int width, int height, int codeCount, int lineCount, char[] codeSequence) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        this.lineCount = lineCount;
        this.codeSequence = codeSequence;
        this.createCode(Color.WHITE);
    }

    public void createCode(Color color) {
        int codeX = 0;
        int fontHeight = 0;
        fontHeight = height - 5;// 字体的高度
        codeX = (width - (codeCount * fontWidth)) / 2;// 两边间隔

        // 图像buffer
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();

        // 将图像填充为白色Color.WHITE
        g.setColor(color);
        g.fillRect(0, 0, width, height);

        // 创建字体
        ImgFontByte imgFont = new ImgFontByte();
        Font font = imgFont.getFont(fontHeight);
        g.setFont(font);

        // 绘制干扰线
        for (int i = 0; i < lineCount; i++) {
            int xs = getRandomNumber(width);
            int ys = getRandomNumber(height);
            int xe = xs + getRandomNumber(width / 8);
            int ye = ys + getRandomNumber(height / 8);
            g.setColor(getRandomColor());
            g.drawLine(xs, ys, xe, ye);
        }

        StringBuffer randomCode = new StringBuffer();
        // 随机产生验证码字符
        for (int i = 0; i < codeCount; i++) {
            String strRand = String.valueOf(codeSequence[random
                    .nextInt(codeSequence.length)]);
            // 设置字体颜色
            g.setColor(color());
            // 设置字体位置
            g.drawString(strRand, i * fontWidth + codeX,
                    getRandomNumber(10) + 30);
            randomCode.append(strRand);
        }
        code = randomCode.toString();
    }

    /**
     * 获取随机颜色
     */
    private Color getRandomColor() {
        int r = getRandomNumber(255);
        int g = getRandomNumber(255);
        int b = getRandomNumber(255);
        return new Color(r, g, b);
    }

    private Color color() {
        int[] color = COLOR[random.nextInt(COLOR.length)];
        return new Color(color[0], color[1], color[2]);
    }

    /**
     * 获取随机数
     */
    private int getRandomNumber(int number) {
        return random.nextInt(number);
    }

    public void write(String path) throws IOException {
        OutputStream sos = new FileOutputStream(path);
        this.write(sos);
    }

    public void write(OutputStream sos) throws IOException {
        ImageIO.write(buffImg, "png", sos);
        sos.close();
    }

    public BufferedImage getBuffImg() {
        return buffImg;
    }

    public String getCode() {
        return code;
    }

    /**
     * 字体样式类
     */
    class ImgFontByte {
        public Font getFont(int fontHeight) {
            try {
                Font baseFont = Font.createFont(Font.TRUETYPE_FONT,
                        new ByteArrayInputStream(hex2byte(getFontByteStr())));
                return baseFont.deriveFont(Font.PLAIN, fontHeight);
            } catch (Exception e) {
                return new Font("Arial", Font.PLAIN, fontHeight);
            }
        }

        private byte[] hex2byte(String str) {
            if (str == null)
                return null;
            str = str.trim();
            int len = str.length();
            if (len == 0 || len % 2 == 1)
                return null;

            byte[] b = new byte[len / 2];
            try {
                for (int i = 0; i < str.length(); i += 2) {
                    b[i / 2] = (byte) Integer.decode(
                            "0x" + str.substring(i, i + 2)).intValue();
                }
                return b;
            } catch (Exception e) {
                return null;
            }
        }

        // 字体文件的十六进制字符串
        private String getFontByteStr() {

            return "0001000000100040000400c04f532f327d8175d4000087740000005650434c5461e3d9fb000087cc00000036636d61709cbc69ab00007a64000005e863767420bb32bf1600000f";
        }
    }
}
